package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/8 20:23
 * https://leetcode-cn.com/problems/intersection-of-two-linked-lists-lcci/
 */
public class Title07 {

    class ListNode {
        int val;

        ListNode next;

        public ListNode() {
        }

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = 0;
        int lenB = 0;
        ListNode curA = headA;
        ListNode curB = headB;
        while (curA != null) {
            lenA++;
            curA = curA.next;
        }
        while (curB != null) {
            lenB++;
            curB = curB.next;
        }
        //让lenA为大
        if (lenA < lenB) {
            int temp = lenA;
            lenA = lenB;
            lenB = temp;
            ListNode t = headA;
            headA = headB;
            headB = t;
        }
        int gap = lenA - lenB;
        curA = headA;
        curB = headB;
        for (int i = 0; i < gap; i++) {
            curA = curA.next;
        }
        while (curA != curB && curA != null) {
            curA = curA.next;
            curB = curB.next;
        }
        if (curA == null) {
            return null;
        } else {
            return curA;
        }
    }








    public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        int lenA = 0, lenB = 0;
        ListNode curA = headA, curB = headB;
        while (curA != null) {
            lenA++;
            curA = curA.next;
        }
        while (curB != null) {
            lenB++;
            curB = curB.next;
        }
        //A最大
        int temp;
        curA = headA;
        curB = headB;
        ListNode tempNode;
        if (lenA < lenB) {
            temp = lenA;
            lenA = lenB;
            lenB = temp;
            tempNode = curA;
            curA = curB;
            curB = tempNode;
        }
        //移动长度最长的链表 curA
        int gap = lenA - lenB;
        for (int i = 0; i < gap; i++) {
            curA = curA.next;
        }
        while (curA != null) {
            if (curA == curB) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }


















    public static void main(String[] args) {

    }
}
